import { addOneGoods, getShoppingCart } from '~/api/cart'
import { getToken } from '~/utils/jwt'
import Cookies from 'js-cookie'

export const state = () => ({
  shoppingCart: [], // 购物车
  tempShoppingCart: [], // 临时购物车
  newShoppingCart: [] // 刚加入的购物车，作为添加完成的展示
})

export const mutations = {
  // 添加成功页面的购物车数据
  ADD_NEW_SHOPPING_CART(state, data) {
    const item = {
      gid: data.gid,
      count: data.count
    }
    state.newShoppingCart = [item]
    // 临时购物车保存30分钟
    Cookies.set('newShoppingCart', JSON.stringify(state.newShoppingCart), { expires: 1 / 24 / 2 })
  },
  // 添加商品进入临时购物车
  ADD_TEMP_SHOPPING_CART(state, data) {
    const item = {
      gid: data.gid,
      count: data.count
    }
    // 判断是否已有该商品id，有的话数量增加
    let index = -1
    state.tempShoppingCart.forEach((currentValue, i, arr) => {
      if (currentValue.gid === item.gid) {
        index = i
      }
    })
    if (index !== -1) {
      state.tempShoppingCart[index].count += item.count
    } else {
      state.tempShoppingCart.push(item)
    }
    Cookies.set('tempCarts', JSON.stringify(state.tempShoppingCart))
  },

  // 设置临时购物车信息
  SET_TEMP_SHOPPING_CART(state, data) {
    state.tempShoppingCart = data
    Cookies.set('tempCarts', JSON.stringify(data))
  },
  EDIT_TEMP_SHOPPING_CART(state, obj) {
    let index = -1
    state.tempShoppingCart.forEach((currentValue, i, arr) => {
      if (parseInt(currentValue.gid) === obj.goods_id) {
        index = i
      }
    })
    state.tempShoppingCart[index].count = obj.value
    Cookies.set('tempCarts', JSON.stringify(state.tempShoppingCart))
  },
  DELETE_TEMP_SHOPPING_CART(state, gid) {
    let index = -1
    state.tempShoppingCart.forEach((currentValue, i, arr) => {
      if (parseInt(currentValue.gid) === gid) {
        index = i
      }
    })
    state.tempShoppingCart.splice(index, 1)
    Cookies.set('tempCarts', JSON.stringify(state.tempShoppingCart))
  }
}

export const actions = {
  // 添加购物车
  addShoppingCart({ commit, rootState }, data) {
    return new Promise((resolve, reject) => {
      const token = getToken()
      if (token) {
        commit('ADD_NEW_SHOPPING_CART', data)
        const uid = rootState.user.userInfo.uid
        // 已经登录，发出添加购物车请求
        addOneGoods({
          uid,
          qty: data.count,
          gid: data.gid
        }).then(res => {
          if (res.code === 200) {
            resolve('success')
          } else {
            resolve('faild')
          }
        })
      } else {
        // 添加临时购物车--更新state与cookie，同时也更新添加成功页数据
        commit('ADD_TEMP_SHOPPING_CART', data)
        commit('ADD_NEW_SHOPPING_CART', data)
        resolve('success')
      }
    })
  },

  // 加载购物车
  getShoppingCart({ commit, rootState }) {
    return new Promise((resolve, reject) => {
      const token = getToken()
      if (token) {
        const uid = rootState.user.userInfo.uid
        // 获取数据库的购物车数据
        getShoppingCart(uid).then(res => {
          resolve(res)
        })
      } else {
        // 临时购物车的数据
        let tempData = []
        if (Cookies.get('tempCarts')) {
          tempData = JSON.parse(Cookies.get('tempCarts'))
        }
        // 未登录情况只需要获取cookie中的临时购物车数据，并存入vuex,然后根据这些商品id批量查询
        commit('SET_TEMP_SHOPPING_CART', tempData)
        resolve()
      }
    })
  },
  editStoreShoppingCart({ commit }, obj) {
    commit('EDIT_TEMP_SHOPPING_CART', obj)
  },
  deleteStoreShoppingCart({ commit }, gid) {
    commit('DELETE_TEMP_SHOPPING_CART', gid)
  }

}
